package com.qcby.util;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class WordWriter {
    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

//    生成word
    public static byte[] generateWordDocument(String markdownText) throws IOException {
    try (XWPFDocument document = new XWPFDocument();
         ByteArrayOutputStream out = new ByteArrayOutputStream()) {

        // 按行分割文本
        String[] lines = markdownText.split("\n");

        for (String line : lines) {
            // 处理段落
            XWPFParagraph paragraph = document.createParagraph();

            // 判断是否是标题行（根据#数量）
            if (line.startsWith("###")) {
                paragraph.setStyle("Heading3");
                line = line.replace("###", "").trim();
            } else if (line.startsWith("##")) {
                paragraph.setStyle("Heading2");
                line = line.replace("##", "").trim();
            } else if (line.startsWith("#")) {
                paragraph.setStyle("Heading1");
                line = line.replace("#", "").trim();
            }

            // 处理加粗文本
            processMarkdownBoldText(paragraph, line);
        }

        document.write(out);
        return out.toByteArray();
    }
}
    public String uploadDoc(String content,String originalFilename) throws Exception {
        byte[] bytes = generateWordDocument(content);
        String url = aliyunOSSOperator.upload(bytes, originalFilename);
        return url;
    }

    /**
     * 处理Markdown加粗语法并设置格式
     */
    private static void processMarkdownBoldText(XWPFParagraph paragraph, String text) {
        // 使用正则匹配 **加粗内容**
        Pattern pattern = Pattern.compile("\\*\\*(.+?)\\*\\*");
        Matcher matcher = pattern.matcher(text);
        int lastIndex = 0;

        while (matcher.find()) {
            // 添加普通文本
            if (matcher.start() > lastIndex) {
                XWPFRun normalRun = paragraph.createRun();
                normalRun.setText(text.substring(lastIndex, matcher.start()));
            }

            // 添加加粗文本
            XWPFRun boldRun = paragraph.createRun();
            boldRun.setText(matcher.group(1));
            boldRun.setBold(true);
            boldRun.setFontSize(14);

            lastIndex = matcher.end();
        }

        // 添加剩余文本
        if (lastIndex < text.length()) {
            XWPFRun lastRun = paragraph.createRun();
            lastRun.setText(text.substring(lastIndex));
        }
    }




}